package cn.time1024.time_app.data.api

import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL

/**
 * 工作流API客户端：通过HttpURLConnection简易封装后端接口调用。
 * - 基础能力：查询列表、创建、更新、删除、运行。
 */
class WorkflowApiClient(private val baseUrl: String) {

    /**
     * 查询全部工作流。
     */
    fun fetchAll(): List<WorkflowDto> {
        val url = URL("$baseUrl/time/coze/workflows")
        val conn = url.openConnection() as HttpURLConnection
        conn.requestMethod = "GET"
        conn.connectTimeout = 5000
        conn.readTimeout = 5000
        try {
            val code = conn.responseCode
            if (code != 200) return emptyList()
            val br = BufferedReader(InputStreamReader(conn.inputStream))
            val body = br.readText()
            val arr = JSONArray(body)
            val list = mutableListOf<WorkflowDto>()
            for (i in 0 until arr.length()) {
                val o = arr.getJSONObject(i)
                list.add(WorkflowDto.fromJson(o))
            }
            return list
        } catch (e: Exception) {
            Log.e("WorkflowApiClient", "fetchAll error", e)
            return emptyList()
        } finally {
            conn.disconnect()
        }
    }

    /**
     * 创建工作流。
     */
    fun create(name: String, description: String?, content: String?): WorkflowDto? {
        val url = URL("$baseUrl/time/coze/workflows")
        val conn = url.openConnection() as HttpURLConnection
        conn.requestMethod = "POST"
        conn.setRequestProperty("Content-Type", "application/json")
        conn.doOutput = true
        try {
            val payload = JSONObject()
            payload.put("name", name)
            payload.put("description", description)
            payload.put("content", content)
            OutputStreamWriter(conn.outputStream).use { it.write(payload.toString()) }
            val code = conn.responseCode
            if (code != 200 && code != 201) return null
            val body = BufferedReader(InputStreamReader(conn.inputStream)).readText()
            return WorkflowDto.fromJson(JSONObject(body))
        } catch (e: Exception) {
            Log.e("WorkflowApiClient", "create error", e)
            return null
        } finally {
            conn.disconnect()
        }
    }

    /**
     * 更新工作流。
     */
    fun update(id: Long, name: String?, description: String?, content: String?): WorkflowDto? {
        val url = URL("$baseUrl/time/coze/workflows/$id")
        val conn = url.openConnection() as HttpURLConnection
        conn.requestMethod = "PUT"
        conn.setRequestProperty("Content-Type", "application/json")
        conn.doOutput = true
        try {
            val payload = JSONObject()
            payload.put("name", name)
            payload.put("description", description)
            payload.put("content", content)
            OutputStreamWriter(conn.outputStream).use { it.write(payload.toString()) }
            val code = conn.responseCode
            if (code != 200) return null
            val body = BufferedReader(InputStreamReader(conn.inputStream)).readText()
            return WorkflowDto.fromJson(JSONObject(body))
        } catch (e: Exception) {
            Log.e("WorkflowApiClient", "update error", e)
            return null
        } finally {
            conn.disconnect()
        }
    }

    /**
     * 删除工作流。
     */
    fun delete(id: Long): Boolean {
        val url = URL("$baseUrl/time/coze/workflows/$id")
        val conn = url.openConnection() as HttpURLConnection
        conn.requestMethod = "DELETE"
        try {
            val code = conn.responseCode
            return code == 204 || code == 200
        } catch (e: Exception) {
            Log.e("WorkflowApiClient", "delete error", e)
            return false
        } finally {
            conn.disconnect()
        }
    }

    /**
     * 运行工作流。
     */
    fun run(id: Long): RunResultDto? {
        val url = URL("$baseUrl/time/coze/workflows/$id/run")
        val conn = url.openConnection() as HttpURLConnection
        conn.requestMethod = "POST"
        try {
            val code = conn.responseCode
            if (code != 200) return null
            val body = BufferedReader(InputStreamReader(conn.inputStream)).readText()
            val o = JSONObject(body)
            return RunResultDto(
                workflowId = o.optLong("workflowId"),
                startedAt = o.optString("startedAt"),
                success = o.optBoolean("success"),
                output = o.optString("output")
            )
        } catch (e: Exception) {
            Log.e("WorkflowApiClient", "run error", e)
            return null
        } finally {
            conn.disconnect()
        }
    }

    /**
     * 工作流DTO。
     */
    data class WorkflowDto(
        val id: Long,
        val name: String?,
        val description: String?,
        val content: String?,
        val status: String?,
        val createdAt: String?,
        val updatedAt: String?
    ) {
        companion object {
            fun fromJson(o: JSONObject): WorkflowDto {
                return WorkflowDto(
                    id = o.optLong("id"),
                    name = o.optString("name"),
                    description = o.optString("description"),
                    content = o.optString("content"),
                    status = o.optString("status"),
                    createdAt = o.optString("createdAt"),
                    updatedAt = o.optString("updatedAt")
                )
            }
        }
    }

    /**
     * 运行结果DTO。
     */
    data class RunResultDto(
        val workflowId: Long,
        val startedAt: String,
        val success: Boolean,
        val output: String
    )
}